
var uploader = {
    'data':{
        'token':'',
        'uploadDomain':'',
        'domain':''
    },
    'complete':function(res){
        var url="http://"+uploader.data.domain +"/"+ res.key;

        // $(".pic-pic").attr("src",url);
        // $(".hidden-pic").val(url);
        var barimg = '<div class="banner-css" style="display:inline-block;">\n' +
            '<label><b class="btn" onclick="delbanner(this)">X</b><img class="detail-img" src="'+url+'" class="banner-pic"></label>\n' +
            '<input type="hidden" name="list_img[]" value="'+res.key+'" class="hidden-picc">\n' +
            '</div>';
        $('.default').val('');
        $('.banner-img').append(barimg);
    },

    'complete2':function(res){
        var url="http://"+uploader.data.domain +"/"+ res.key;
        $(".pic3").attr("src",url);
        $(".hidden-pic3").val(res.key);
    },
    'complete3':function(res){
        var imgval = '.imgindex'+res['x:img'];
        console.log(imgval)
        var url="http://"+uploader.data.domain +"/"+ res.key;
        $(imgval).val(res.key)
    },
    'error':function () {
        console.dir(arguments);
    },
    // 分片上传时的进度展示功能在此书写.
    'next':function (response) {
        // var chunks = response.chunks || [];
        // var total = response.total;
    },
    'init':function(){
        $.ajax({
            'url':'/upload/get-token',
            'type':'POST',
            'dataType':'json',
            'success':function(data){
                if(data.code != 200)
                {
                    layer.alert(data.msg);
                    return false;
                }
                uploader.data.token = data.data.token;      // token
                uploader.data.domain = data.data.domain;    // 显示域名
                // uploader.data.uploadDomain = 'idv093d.qiniudns.com';    // 上传域名
            }
        });
    },
    'eventBind':function(){
        this.init();
        $('.default').on('change',function () {
            var token = uploader.data.token;
            var config = {
                useCdnDomain: true,
                disableStatisticsReport: false,
                region: qiniu.region.z0
            };
            var putExtra = {
                fname: "",
                params: {},
                mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
            };
            var file = this.files[0];
            var observable;

            if (file) {
                var files=$(".default")[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                var key1=file.name;
                var key=key1.split(".")[0]+randomNum()+"."+key1.split(".")[1];
                putExtra.params["x:name"] = key.split(".")[0];
                // 配置完成的数组.
                var subObject = {
                    next: uploader.next,
                    error: uploader.error,
                    complete: uploader.complete
                };
                var subscription;
                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                observable = qiniu.upload(files, key, token, putExtra, config);
                subscription = observable.subscribe(subObject);
                // subscription.unsubscribe();  // 取消上传.
            }
        });

        $('.pic-card3').on('change',function () {
            var token = uploader.data.token;
            var config = {
                useCdnDomain: true,
                disableStatisticsReport: false,
                region: qiniu.region.z0
            };
            var putExtra = {
                fname: "",
                params: {},
                mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
            };
            var file = this.files[0];
            var observable;
            if (file) {
                var files=$(this)[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                var key1=file.name;
                var key=key1.split(".")[0]+randomNum()+"."+key1.split(".")[1];
                putExtra.params["x:name"] = key.split(".")[0];
                // 配置完成的数组.
                var subObject = {
                    next: uploader.next,
                    error: uploader.error,
                    complete: uploader.complete2
                };
                var subscription;
                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                observable = qiniu.upload(files, key, token, putExtra, config);
                subscription = observable.subscribe(subObject);
                // subscription.unsubscribe();  // 取消上传.
            }
        });

        $('body').on('change','.pic-card4',function () {
            var imgthis = $(this).attr('indexs');

            var token = uploader.data.token;
            var config = {
                useCdnDomain: true,
                disableStatisticsReport: false,
                region: qiniu.region.z0
            };
            var putExtra = {
                fname: "",
                params: {},
                mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
            };
            var file = this.files[0];
            var observable;
            if (file) {
                var files=$(this)[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                var key1=file.name;
                var key=key1.split(".")[0]+randomNum()+"."+key1.split(".")[1];
                putExtra.params["x:name"] = key.split(".")[0];
                putExtra.params["x:img"] = imgthis;
                // 配置完成的数组.
                var subObject = {
                    next: uploader.next,
                    error: uploader.error,
                    complete: uploader.complete3
                };
                var subscription;
                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                observable = qiniu.upload(files, key, token, putExtra, config);
                subscription = observable.subscribe(subObject);
                // subscription.unsubscribe();  // 取消上传.
            }
        });
    }
};

$('.introductions').on('keydown',function () {
    var indexs = 220;
    var texts = $(this).val().length;
    indexs = indexs-texts;
    if(indexs < 0){
        layer.alert('已超过220个字符');
    }
    $('.testcount').html(indexs);
})



function delbanner($this) {
    if(confirm('确定删除当前图片？')){
        $($this).parents('.banner-css').remove();
    }
}

//三级联动
$('.oneclass').change(function () {
    var classid = $(".oneclass option:selected").val();
    $('.twoclass').html('');
    $('.threeclass').html('');
    changeclassAjax('.twoclass',classid,'一')
})

$('.twoclass').change(function () {
    var classid = $(".twoclass option:selected").val();
    $('.threeclass').html('');
    changeclassAjax('.threeclass',classid,'二')
})
function changeclassAjax(calsss,id,num) {
    $.ajax({
        'url': '/goods/get-tree',
        'type': 'POST',
        'dataType': 'json',
        'data': {id:id},
        'success': function (data) {
            if (data.code != 200) {
                layer.alert(data.msg);
                return false;
            } else {
                var option = '<option value="0">请选择'+num+'级分类</option>';
                $.each(data.data,function(indexe,value){
                    option += '<option value="'+value.id+'">'+value.tree_name+'</option>'
                });
                $(calsss).append(option);
            }
        }
    });
}



$(document).ready(function(){

    uploader.eventBind();

    //传递数据
    $(".btn-last-googs").on("click",function(){
        var newattr = [];
        var thd=[],tby=[];
        // $(".thead").find('th').each(function(i){
        //     var th_val=$(".thead").find('th').eq(i).text();
        //     thd.push(th_val);
        // })
        $(".tbody").find('tr').each(function(i){
            var td_val=[]
            $(".tbody").find('tr').eq(i).find('.need').each(function(j){
                var needVal=$(".tbody").find('tr').eq(i).find('.need').eq(j).val();
                if(needVal){
                    td_val.push(needVal);
                }else{
                    td_val.push(0);
                }
                
            })
            tby.push(td_val)
        })
        
        var threeid = $(".threeclass option:selected").val();  //三级分类
        var twoid = $(".twoclass option:selected").val();  //二级分类
        var oneid = $(".oneclass option:selected").val();  //一级分类
        var goods_name = $(":input[name='goods_name']").val();
        var type = $(":input[name='type']").val();
        var key = $(":input[name='key']").val();
        var list_img = $(":input[name='list_img']").val();
        var attr_name = $(":input[name='attr_name']").val();
        var introduction = $("#introduction").val();
        // var content = UE.getEditor('editor').getContent();
        var freight = $(":input[name='freight']").val();
            freight = freight>0?freight:0;
        var banner = new Array();

        $('.hidden-picc').each(function($i){
            banner[$i] = $(this).val();
        });

        data = {'goods_name':goods_name,'type':type,'key':key,'list_img':list_img,'introduction':introduction,
            'attr_name':attr_name,'banner':banner,'two_tree_id':twoid,'one_tree_id':oneid,'three_tree_id':threeid,'freight':freight,tby:tby
        };
        flag = true;
        if(threeid == 0){
            layer.msg("请选择三级分类");
            flag = false;
        }else if(goods_name == ""){
            layer.msg("请输入商品名称");
            flag = false;
        }else if(list_img == ''){
            layer.msg("请上传封面图");
            flag = false;
        }else if(banner.length == 0){
            layer.msg("请添加详情图");
            flag = false;
        }
        if(flag) {
            $.ajax({
                'url': '/goods/add',
                'type': 'POST',
                'dataType': 'json',
                'data': data,
                'success': function (data) {
                    if (data.code != 200) {
                        layer.alert(data.msg);
                        return false;
                    } else {
                        layer.msg(data.msg);
                        setTimeout(function(){
                            location.href="/goods/index";
                        },1000);
                    }

                }
            });
        }
    });
})